package com.mrd.gtimpframe.service.impl;

import com.mrd.SMSUtil;
import com.mrd.gtimp.base.entity.User;
import com.mrd.gtimpframe.entity.Dictionary;
import com.mrd.gtimpframe.entity.UserService;
import com.mrd.gtimpframe.service.DictionaryService;
import com.mrd.gtimpframe.service.PhoneNOBindingService;
import com.mrd.gtimpframe.service.UserServiceService;
import com.mrd.redis.JedisClientClusterImpl;
import com.mrd.util.LoginUtil;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by dusy on 2017/7/20.
 */
@Service
public class PhoneNOBindingServiceImpl implements PhoneNOBindingService {
    @Autowired
    private JedisClientClusterImpl jedisClientCluster;
    @Autowired
    private UserServiceService userServiceService;
    @Autowired
    private DictionaryService dictionaryService;
    @Value("${binding.code.deadTime}")
    private String codeDeadTime;
    @Value("${binding.code.dictionary.group}")
    private String SMSTemplateDictionaryGroup;
    @Value("${binding.code.dictionary.template}")
    private String SMSTemplateDictionaryCode;
    @Value("${sms.userId}")
    private String userId;
    @Value("${sms.password}")
    private String password;

    @Override
    public boolean checkPhoneNOBinding() {
        User user = LoginUtil.getLoginUser();
        UserService userService = new UserService();
        userService.setUserId(user.getId());
        userService.setServerType("SMS");
        userService.setStatus("1");
        List<UserService> userServiceList = userServiceService.selectSelective(userService);
        if (userServiceList != null && userServiceList.size() > 0) {
            return true;
        }
        return false;
    }

    @Override
    public String getPhoneValidCode(String phoneNO) {
        String code = String.format("%04d", (int) (10000 * Math.random()));
        List<Dictionary> dictionaries = dictionaryService.selectWithDictionaryByCodesIn(SMSTemplateDictionaryGroup);
        String context = "手机绑定验证码：" + code;
        if (dictionaries != null) {
            for (Dictionary dictionary : dictionaries) {
                if (SMSTemplateDictionaryCode.equals(dictionary.getDictionaryCode())) {
                    context = dictionary.getDictionaryName().replace("[验证码]", code);
                    break;
                }
            }
        }
        SMSUtil.sendMessage(userId, password, phoneNO, context);
        Long endTime = 90L;
        try {
            endTime = Long.parseLong(codeDeadTime);
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }
        jedisClientCluster.set("code_" + phoneNO, code, endTime, TimeUnit.SECONDS);
        return jedisClientCluster.get("code_" + phoneNO, String.class);
    }

    @Override
    public String bindPhone(String validCode, String phoneNO, String acceptMessage) {
        String code = jedisClientCluster.get("code_" + phoneNO, String.class);
        if (StringUtils.isEmpty(code)) {
            return "验证码已过期";
        } else if (code.equals(validCode)) {
            User user = LoginUtil.getLoginUser();
            UserService userService = new UserService();
            userService.setUserId(user.getId());
            userService.setServerType("SMS");
            userService.setStatus("1");
            List<UserService> userServiceList = userServiceService.selectSelective(userService);
            if ("true".equals(acceptMessage)) {
                userService.setVerified("1");
            } else if ("false".equals(acceptMessage)) {
                userService.setVerified("0");
            }
            userService.setDeviceCode(phoneNO);
            if (userServiceList == null || userServiceList.size() == 0) {
                userService.setId(com.mrd.util.StringUtils.getUUID());
                userServiceService.insertSelective(userService);
            } else {
                userService.setId(userServiceList.get(0).getId());
                userServiceService.updateByPrimaryKeySelective(userService);
            }
            return "0";
        }
        return "验证码错误";
    }

    /**
     * 解除绑定
     */
    @Override
    public void unbindPhoneNO() {
        User user = LoginUtil.getLoginUser();
        UserService userService = new UserService();
        userService.setUserId(user.getId());
        userService.setServerType("SMS");
        userService.setStatus("1");
        List<UserService> userServiceList = userServiceService.selectSelective(userService);
        if (userServiceList != null && userServiceList.size() > 0) {
            userServiceService.deleteByPrimaryKey(userServiceList.get(0).getId());
        }
    }

    /**
     * 接收信息更改
     */
    @Override
    public String acceptMsg() {
        User user = LoginUtil.getLoginUser();
        UserService userService = new UserService();
        userService.setUserId(user.getId());
        userService.setServerType("SMS");
        userService.setStatus("1");
        List<UserService> userServiceList = userServiceService.selectSelective(userService);
        if (userServiceList == null || userServiceList.size() == 0) {
            return "当前没有绑定手机号码";
        } else {
            userService = userServiceList.get(0);
            if ("1".equals(userService.getVerified())) {
                userService.setVerified("0");
            } else {
                userService.setVerified("1");
            }
        }
        userServiceService.updateByPrimaryKeySelective(userService);
        return "修改成功";
    }
}

